package com.ph.shopping.facade.profit.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ph.shopping.common.core.base.BaseService;
import com.ph.shopping.common.core.customenum.MessageEnum;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.core.exception.BizException;
import com.ph.shopping.common.util.calculation.ProfitCalculation;
import com.ph.shopping.common.util.constants.TableNameContants;
import com.ph.shopping.common.util.page.PageBean;
import com.ph.shopping.common.util.result.MessageInfo;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.common.util.transform.MoneyTransUtil;
import com.ph.shopping.common.util.verifycode.VerifyUtil;
import com.ph.shopping.facade.mapper.IHunterMapper;
import com.ph.shopping.facade.mapper.IUnlineManagerProfitMapper;
import com.ph.shopping.facade.mapper.IUnlineOrderProfitMapper;
import com.ph.shopping.facade.profit.dto.PositionDto;
import com.ph.shopping.facade.profit.entity.HunterEntity;
import com.ph.shopping.facade.profit.entity.UnlineManagerProfit;
import com.ph.shopping.facade.profit.entity.UnlineSupplyChainProfit;
import com.ph.shopping.facade.profit.request.HunterRequest;
import com.ph.shopping.facade.profit.service.IProfitService;
import com.ph.shopping.facade.profit.vo.AgentVo;
import com.ph.shopping.facade.profit.vo.AgentWithdrawalsVo;
import com.ph.shopping.facade.profit.vo.HunterProfitVo;
import com.ph.shopping.facade.profit.vo.MerchantOrderVo;
import com.ph.shopping.facade.profit.vo.MerchantVo;
import com.ph.shopping.facade.profit.vo.MerchantWithdrawalsVo;
import com.ph.shopping.facade.profit.vo.UnlineManagerProfitVo;

@Component
@Service(version = "1.0.0")
public class ProfitServiceImpl extends BaseService implements IProfitService {

	@Autowired
	IUnlineOrderProfitMapper iUnlineOrderProfitMapper;

	@Autowired
	private IUnlineManagerProfitMapper iUnlineManagerProfitMapper;

	@Autowired
	private IHunterMapper iHunterMapper;

	/**
	 * 线下供应链订单分润表
	 */
	@Override
	public Result getUnlineOrderSupplyChainProfitVoList(UnlineSupplyChainProfit unlineSupplyChainProfit,
			PageBean pagebean) {
		PageHelper.startPage(pagebean.getPageNum(), pagebean.getPageSize());
		List<UnlineSupplyChainProfit> unlineOrderSupplyChainProfitList = iUnlineOrderProfitMapper
				.getUnlineOrderSupplyChainProfitList(unlineSupplyChainProfit.getOrderNo(),
						unlineSupplyChainProfit.getOrderType());
		// 出库除一下 除10000
		for (UnlineSupplyChainProfit m : unlineOrderSupplyChainProfitList) {
			m.setPrice(MoneyTransUtil.transDivisDouble(m.getPrice1()));
			m.setCost(MoneyTransUtil.transDivisDouble(m.getCost1()));
			m.setBuyExpense(MoneyTransUtil.transDivisDouble(m.getBuyExpense1()));
			m.setLogisticsFee(MoneyTransUtil.transDivisDouble(m.getLogisticsFee1()));
			m.setChainProfit(MoneyTransUtil.transDivisDouble(m.getChainProfit1()));
			m.setPhIncome(MoneyTransUtil.transDivisDouble(m.getPhIncome1()));
			m.setYstIncome(MoneyTransUtil.transDivisDouble(m.getYstIncome1()));
			m.setCityProfit(MoneyTransUtil.transDivisDouble(m.getCityProfit1()));
			m.setCountyProfit(MoneyTransUtil.transDivisDouble(m.getCountyProfit1()));
			m.setCommunityProfit(MoneyTransUtil.transDivisDouble(m.getCommunityProfit1()));
			m.setChainTotal(MoneyTransUtil.transDivisDouble(m.getChainTotal1()));
			m.setChainRemain(MoneyTransUtil.transDivisDouble(m.getChainRemain1()));
			m.setYstRemain(MoneyTransUtil.transDivisDouble(m.getYstRemain1()));
			m.setPhRemain(MoneyTransUtil.transDivisDouble(m.getPhRemain1()));

		}
		PageInfo<UnlineSupplyChainProfit> pageInfo = new PageInfo<UnlineSupplyChainProfit>(
				unlineOrderSupplyChainProfitList);
		return getResult(ResultEnum.SUCCESS, pageInfo.getList(), pageInfo.getTotal());
	}

	/**
	 * 导出线下订单供应链利润分成表EXCEL
	 * 
	 * @return
	 */
	public Result exportUnlineOrderSupplyChainProfit() {
		List<UnlineSupplyChainProfit> ex = iUnlineOrderProfitMapper.exportUnlineOrderSupplyChainProfit();
		// 出库除一下 除10000
		for (UnlineSupplyChainProfit m : ex) {
			m.setPrice(MoneyTransUtil.transDivisDouble(m.getPrice1()));
			m.setCost(MoneyTransUtil.transDivisDouble(m.getCost1()));
			m.setBuyExpense(MoneyTransUtil.transDivisDouble(m.getBuyExpense1()));
			m.setLogisticsFee(MoneyTransUtil.transDivisDouble(m.getLogisticsFee1()));
			m.setChainProfit(MoneyTransUtil.transDivisDouble(m.getChainProfit1()));
			m.setPhIncome(MoneyTransUtil.transDivisDouble(m.getPhIncome1()));
			m.setYstIncome(MoneyTransUtil.transDivisDouble(m.getYstIncome1()));
			m.setCityProfit(MoneyTransUtil.transDivisDouble(m.getCityProfit1()));
			m.setCountyProfit(MoneyTransUtil.transDivisDouble(m.getCountyProfit1()));
			m.setCommunityProfit(MoneyTransUtil.transDivisDouble(m.getCommunityProfit1()));
			m.setChainTotal(MoneyTransUtil.transDivisDouble(m.getChainTotal1()));
			m.setChainRemain(MoneyTransUtil.transDivisDouble(m.getChainRemain1()));
			m.setYstRemain(MoneyTransUtil.transDivisDouble(m.getYstRemain1()));
			m.setPhRemain(MoneyTransUtil.transDivisDouble(m.getPhRemain1()));
		}
		return getResult(ResultEnum.SUCCESS, ex);
	}

	/**
	 * 
	 * Title: insertUnLineOrderProfit Description:新增线下订单普惠管理费利润分成
	 * 
	 * @author WQiang
	 * @date 2017年3月27日 下午3:08:29
	 * @param unlineManagerProfit
	 * @return
	 * @throws Exception
	 * @see com.ph.shopping.facade.profit.service.IProfitService#insertUnLineOrderProfit(java.util.List)
	 */
	@Override
	public int insertUnLineOrderProfit(List<UnlineManagerProfit> unlineManagerProfit) throws Exception {
		return iUnlineManagerProfitMapper.insert(unlineManagerProfit);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result executiveUnLineOrderSupplyChainProfit() throws BizException {
		Result result = getResult(ResultEnum.SUCCESS);
		try {
			logger.info("开始执行线下订单供应链利润分润");
			// 周一问看这个状态的情况此处我用的是状态4
			List<MerchantOrderVo> merchantOrderVoList = iUnlineOrderProfitMapper.getUnLineOrderSupplyChainProfit();
			if (null == merchantOrderVoList || merchantOrderVoList.size() < 1) {
				logger.debug("无分润的数据");
				return result;
			}
			// 处理数据
			List<UnlineSupplyChainProfit> unlineSupplyChainProfitList = new ArrayList<UnlineSupplyChainProfit>();
			for (MerchantOrderVo m : merchantOrderVoList) {
				// 出库就除以10000 入库就乘以10000
				UnlineSupplyChainProfit unlineSupplyChainProfit = new UnlineSupplyChainProfit();
				Double A = m.getCommodityRetailPrice() == null ? 0
						: MoneyTransUtil.transDivisDouble(m.getCommodityRetailPrice().longValue());// 零售价
				Double B = m.getSettlementPrice() == null ? 0
						: MoneyTransUtil.transDivisDouble(m.getSettlementPrice().longValue());// 结算价
				Double D = m.getFreight() == null ? 0 : MoneyTransUtil.transDivisDouble(m.getFreight().longValue());// 物流费

				PositionDto positionDto = new PositionDto();
				positionDto.setProvinceId(m.getProvinceId() == null ? -1 : m.getProvinceId());
				positionDto.setCityId(m.getCityId() == null ? -1 : m.getCityId());
				positionDto.setCountyId(m.getCountyId() == null ? -1 : m.getCountyId());
				positionDto.setTownId(m.getTownId() == null ? -1 : m.getTownId());
				// 查询社区代理
				List<AgentVo> commityAgency = iUnlineManagerProfitMapper.queryCommunityAgency(positionDto);
				if (commityAgency.size() == 1) {
					AgentVo agentVo = commityAgency.get(0);
					unlineSupplyChainProfit.setQuName(agentVo.getAgentName());
					unlineSupplyChainProfit.setQuRName(agentVo.getPromoterName());
				}

				// 查询县代理
				List<AgentVo> countyAgency = iUnlineManagerProfitMapper.queryCountyAgency(positionDto);
				if (countyAgency.size() == 1) {
					AgentVo agentVo = countyAgency.get(0);
					unlineSupplyChainProfit.setXianName(agentVo.getAgentName());
					unlineSupplyChainProfit.setXianRName(agentVo.getPromoterName());
				}

				// 查询市代理
				List<AgentVo> cityAgency = iUnlineManagerProfitMapper.queryCityAgency(positionDto);
				if (cityAgency.size() == 1) {
					AgentVo agentVo = cityAgency.get(0);
					unlineSupplyChainProfit.setShiName(agentVo.getAgentName());
					unlineSupplyChainProfit.setShiRName(agentVo.getPromoterName());
				}

				unlineSupplyChainProfit.setBuyerName(m.getBuyerName());
				unlineSupplyChainProfit.setSellerName(m.getSellerName());
				unlineSupplyChainProfit.setOrderNo(m.getOrderNo());// 订单号
				unlineSupplyChainProfit.setPrice1(MoneyTransUtil.transMultiDouble(ProfitCalculation.getPrice(A)));// 零售价
				unlineSupplyChainProfit.setCost1(MoneyTransUtil.transMultiDouble(ProfitCalculation.getCost(B)));// 结算价
				unlineSupplyChainProfit
						.setBuyExpense1(MoneyTransUtil.transMultiDouble(ProfitCalculation.getBuyExpense(A)));
				unlineSupplyChainProfit
						.setLogisticsFee1(MoneyTransUtil.transMultiDouble(ProfitCalculation.getLogisticsFee(D)));
				unlineSupplyChainProfit
						.setChainProfit1(MoneyTransUtil.transMultiDouble(ProfitCalculation.getChainProfit(A)));
				unlineSupplyChainProfit.setPhIncome1(MoneyTransUtil.transMultiDouble(ProfitCalculation.getPhIncome(A)));
				unlineSupplyChainProfit
						.setYstIncome1(MoneyTransUtil.transMultiDouble(ProfitCalculation.getYstIncome(A)));

				long shiDaiFenRun = MoneyTransUtil.transMultiDouble(ProfitCalculation.getCityProfit(A));
				if (unlineSupplyChainProfit.getShiName() == null || "".equals(m.getShiName())) {// 如果没有市级代理
					shiDaiFenRun = 0;
				}
				unlineSupplyChainProfit.setCityProfit1(shiDaiFenRun);

				long xianDaiFenRun = MoneyTransUtil.transMultiDouble(ProfitCalculation.getCountyProfit(A));
				if (unlineSupplyChainProfit.getXianName() == null || "".equals(m.getXianName())) {// 如果没有县级代理
					xianDaiFenRun = 0;
				}
				unlineSupplyChainProfit.setCountyProfit1(xianDaiFenRun);

				long sheDaiFenRun = MoneyTransUtil.transMultiDouble(ProfitCalculation.getCommunityProfit(A));
				if (unlineSupplyChainProfit.getQuName() == null || "".equals(m.getQuName())) {// 如果没有社区代理
					sheDaiFenRun = 0;
				}
				unlineSupplyChainProfit.setCommunityProfit1(sheDaiFenRun);

				unlineSupplyChainProfit.setChainTotal1(shiDaiFenRun + xianDaiFenRun + sheDaiFenRun);// 供应链支出合计

				unlineSupplyChainProfit
						.setChainRemain1(MoneyTransUtil.transMultiDouble(ProfitCalculation.getYstIncome(A))
								- (shiDaiFenRun + xianDaiFenRun + sheDaiFenRun));// 供应链剩余

				unlineSupplyChainProfit
						.setYstRemain1(MoneyTransUtil.transMultiDouble(ProfitCalculation.getBuyExpense(A))
								- MoneyTransUtil.transMultiDouble(ProfitCalculation.getCost(B))
								- MoneyTransUtil.transMultiDouble(ProfitCalculation.getLogisticsFee(D))
								- (shiDaiFenRun + xianDaiFenRun + sheDaiFenRun)
								- MoneyTransUtil.transMultiDouble(ProfitCalculation.getPhIncome(A)));
				unlineSupplyChainProfit.setPhRemain1(MoneyTransUtil.transMultiDouble(ProfitCalculation.getPhRemain(A)));
				unlineSupplyChainProfitList.add(unlineSupplyChainProfit);
			}
			// 接下来执行分润 将数据插入 ph_unline_supplychain_profit 表
			iUnlineOrderProfitMapper.insertUnlineSupplyChainProfitList(unlineSupplyChainProfitList);
			// 接下来更改 ph_merchant_order 字段bonus为2(已分润)
			iUnlineOrderProfitMapper.updateMerchantOrderBonus(merchantOrderVoList);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("线下订单供应链利润分润异常:" + e.getMessage());
			result = getResult(ResultEnum.EXECUTIVE_UNLINEORDERSUPPLYCHAINPROFIT_EXCEPTION);
			throw new BizException("线下订单供应链利润分润异常:90001");
		}
		return result;
	}

	/**
	 * 
	 * Title: handlerManagerFee Description:处理管理费分润
	 * 
	 * @author WQiang
	 * @date 2017年3月27日 下午2:02:14
	 * @see com.ph.shopping.facade.profit.service.IProfitService#handlerManagerFee()
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public String handlerManagerFee() throws Exception {
		List<MerchantVo> merchants = iUnlineManagerProfitMapper.queryMerchant();
		List<UnlineManagerProfit> managerProfits = new ArrayList<UnlineManagerProfit>();
		UnlineManagerProfit profit = null;
		if (VerifyUtil.listIsNotNull(merchants)) {
			for (MerchantVo merchantVo : merchants) {

				profit = new UnlineManagerProfit();
				profit.setSellerName(merchantVo.getSellerName());
				if (VerifyUtil.isNotEmpty(merchantVo.getBuyerName())) {
					profit.setBuyerName(merchantVo.getBuyerName());
				} else {
					profit.setBuyerName(merchantVo.getBuyerTel());
				}

				PositionDto positionDto = new PositionDto();
				positionDto.setProvinceId(merchantVo.getProvinceId());
				positionDto.setCityId(merchantVo.getCityId());
				positionDto.setCountyId(merchantVo.getCountyId());
				positionDto.setTownId(merchantVo.getTownId());

				// 查询社区代理
				List<AgentVo> commityAgency = iUnlineManagerProfitMapper.queryCommunityAgency(positionDto);
				AgentVo agentVo = null;
				if (VerifyUtil.listIsNotNull(commityAgency)) {
					agentVo = commityAgency.get(0);
					profit.setQuName(agentVo.getAgentName());
					profit.setQuRName(agentVo.getPromoterName());

				}
				// 查询县代理
				List<AgentVo> countyAgency = iUnlineManagerProfitMapper.queryCountyAgency(positionDto);
				if (VerifyUtil.listIsNotNull(countyAgency)) {
					agentVo = countyAgency.get(0);
					profit.setXianName(agentVo.getAgentName());
					profit.setXianRName(agentVo.getPromoterName());

				}
				// 查询市代理
				List<AgentVo> cityAgency = iUnlineManagerProfitMapper.queryCityAgency(positionDto);
				if (VerifyUtil.listIsNotNull(cityAgency)) {
					agentVo = cityAgency.get(0);
					profit.setShiName(agentVo.getAgentName());
					profit.setShiRName(agentVo.getPromoterName());
				}

				double X = iUnlineManagerProfitMapper.findMerchantRatio(merchantVo.getOrderNo());
				double A = MoneyTransUtil.transDivisDouble(merchantVo.getOrderMoney());
				profit.setOrderNo(merchantVo.getOrderNo());
				profit.setOrderMoney(merchantVo.getOrderMoney());
				profit.setChargeFee(MoneyTransUtil.transMultiDouble(ProfitCalculation.getChargeFee(X, A)));
				profit.setPhChargeFee(MoneyTransUtil.transMultiDouble(ProfitCalculation.getPhChargeFee(X, A)));
				profit.setYstChargeFee(MoneyTransUtil.transMultiDouble(ProfitCalculation.getYstChargeFee(X, A)));

				if (VerifyUtil.isNotEmpty(profit.getShiName())) {
					profit.setCityAgency(MoneyTransUtil.transMultiDouble(ProfitCalculation.getCityAgency(X, A)));
					if (VerifyUtil.isNotEmpty(profit.getShiRName())) {
						profit.setRecommendCity(
								MoneyTransUtil.transMultiDouble(ProfitCalculation.getRecommendCity(X, A)));
					} else {
						profit.setRecommendCity(0l);
					}
				} else {
					profit.setCityAgency(0l);
					profit.setRecommendCity(0l);
				}

				if (VerifyUtil.isNotEmpty(profit.getXianName())) {
					profit.setCountyAgency(MoneyTransUtil.transMultiDouble(ProfitCalculation.getCountyAgency(X, A)));
					if (VerifyUtil.isNotEmpty(profit.getXianRName())) {
						profit.setRecommendCounty(
								MoneyTransUtil.transMultiDouble(ProfitCalculation.getRecommendCounty(X, A)));
					} else {
						profit.setRecommendCounty(0l);
					}
				} else {
					profit.setCountyAgency(0l);
					profit.setRecommendCounty(0l);
				}

				if (VerifyUtil.isNotEmpty(profit.getQuName())) {
					profit.setCommunityAgency(
							MoneyTransUtil.transMultiDouble(ProfitCalculation.getCommunityAgency(X, A)));
					if (VerifyUtil.isNotEmpty(profit.getQuRName())) {
						profit.setRecommendCommunity(
								MoneyTransUtil.transMultiDouble(ProfitCalculation.getRecommendCommunity(X, A)));
					} else {
						profit.setRecommendCommunity(0l);
					}

				} else {
					profit.setCommunityAgency(0l);
					profit.setRecommendCommunity(0l);
				}

				profit.setMerchantRName(merchantVo.getMerchantRName());
				if (VerifyUtil.isNotEmpty(profit.getMerchantRName())) {
					profit.setRecommendMerchant(
							MoneyTransUtil.transMultiDouble(ProfitCalculation.getRecommendMerchant(X, A)));
				} else {
					profit.setRecommendMerchant(0l);
				}

				long chargeTotal = profit.getCityAgency() + profit.getCountyAgency() + profit.getCommunityAgency()
						+ profit.getRecommendCity() + profit.getRecommendCounty() + profit.getRecommendCommunity()
						+ profit.getRecommendMerchant();

				long chargeRemain = profit.getYstChargeFee() - chargeTotal;

				profit.setChargeTotal(chargeTotal);
				profit.setChargeRemain(chargeRemain);
				profit.setCreateDate(new Date());

				managerProfits.add(profit);
			}

			iUnlineManagerProfitMapper.batchUpdateUnLineOrderSettled(managerProfits);

			int ret = insertUnLineOrderProfit(managerProfits);
			if (ret < 1) {
				throw new Exception("分润失败");
			}

			return "分润成功";
		} else {
			return "暂无分润";
		}
	}

	/**
	 * 
	 * Title: queryAll Description:返回管理费分润结果
	 * 
	 * @author WQiang
	 * @date 2017年3月27日 下午4:14:41
	 * @param orderNo
	 * @param pageNum
	 * @param pageSize
	 * @return
	 * @see com.ph.shopping.facade.profit.service.IProfitService#queryAll(java.lang.String,
	 *      int, int)
	 */
	@Override
	public Result queryAll(String orderNo, int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		List<UnlineManagerProfitVo> list = iUnlineManagerProfitMapper.findAll(orderNo);
		for (UnlineManagerProfitVo managerProfitVo : list) {
			managerProfitVo.setOrderMoney(
					ProfitCalculation.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getOrderMoney1())));
			managerProfitVo.setChargeFee(
					ProfitCalculation.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getChargeFee1())));
			managerProfitVo.setPhChargeFee(
					ProfitCalculation.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getPhChargeFee1())));
			managerProfitVo.setYstChargeFee(ProfitCalculation
					.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getYstChargeFee1())));
			managerProfitVo.setCityAgency(
					ProfitCalculation.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getCityAgency1())));
			managerProfitVo.setCountyAgency(ProfitCalculation
					.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getCountyAgency1())));
			managerProfitVo.setCommunityAgency(ProfitCalculation
					.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getCommunityAgency1())));
			managerProfitVo.setRecommendCity(ProfitCalculation
					.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getRecommendCity1())));
			managerProfitVo.setRecommendCounty(ProfitCalculation
					.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getRecommendCounty1())));
			managerProfitVo.setRecommendCommunity(ProfitCalculation
					.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getRecommendCommunity1())));
			managerProfitVo.setRecommendMerchant(ProfitCalculation
					.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getRecommendMerchant1())));
			managerProfitVo.setChargeTotal(
					ProfitCalculation.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getChargeTotal1())));
			managerProfitVo.setChargeRemain(ProfitCalculation
					.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getChargeRemain1())));
		}
		PageInfo<UnlineManagerProfitVo> pageInfo = new PageInfo<UnlineManagerProfitVo>(list);
		return getResult(ResultEnum.SUCCESS, pageInfo.getList(), pageInfo.getTotal());
	}

	/**
	 * 
	 * Title: findAll Description:导出数据
	 * 
	 * @author WQiang
	 * @date 2017年3月27日 下午7:01:18
	 * @return
	 * @see com.ph.shopping.facade.profit.service.IProfitService#findAll()
	 */
	@Override
	public List<UnlineManagerProfitVo> findAll(String orderNo) {
		List<UnlineManagerProfitVo> list = iUnlineManagerProfitMapper.findAll(orderNo);
		if (VerifyUtil.listIsNotNull(list)) {
			for (UnlineManagerProfitVo managerProfitVo : list) {
				managerProfitVo.setOrderMoney(ProfitCalculation
						.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getOrderMoney1())));
				managerProfitVo.setChargeFee(ProfitCalculation
						.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getChargeFee1())));
				managerProfitVo.setPhChargeFee(ProfitCalculation
						.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getPhChargeFee1())));
				managerProfitVo.setYstChargeFee(ProfitCalculation
						.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getYstChargeFee1())));
				managerProfitVo.setCityAgency(ProfitCalculation
						.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getCityAgency1())));
				managerProfitVo.setCountyAgency(ProfitCalculation
						.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getCountyAgency1())));
				managerProfitVo.setCommunityAgency(ProfitCalculation
						.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getCommunityAgency1())));
				managerProfitVo.setRecommendCity(ProfitCalculation
						.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getRecommendCity1())));
				managerProfitVo.setRecommendCounty(ProfitCalculation
						.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getRecommendCounty1())));
				managerProfitVo.setRecommendCommunity(ProfitCalculation
						.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getRecommendCommunity1())));
				managerProfitVo.setRecommendMerchant(ProfitCalculation
						.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getRecommendMerchant1())));
				managerProfitVo.setChargeTotal(ProfitCalculation
						.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getChargeTotal1())));
				managerProfitVo.setChargeRemain(ProfitCalculation
						.doubleFormat(MoneyTransUtil.transDivisDouble(managerProfitVo.getChargeRemain1())));
			}
			return list;
		} else {
			return null;
		}
	}

	/**
	 * 执行将商户提现记录表的数据插入到线下订单供应链分润记录表
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result executiveMerchantWithdrawalsIntoUnlineSupplychainProfit() {
		Result result = getResult(ResultEnum.SUCCESS);
		try {
			// 查询是否有时间 以此来判断是否是第一次插入时间(查询数量)

			Integer count = iUnlineOrderProfitMapper.selectMerchantWithdrawalsIntoProfitCount(1);
			List<MerchantWithdrawalsVo> merchantWithdrawalsVoList = null;
			if (count > 0) {// 证明不是第一次来执行
				// 查询到最大时间
				Date maxTime = iUnlineOrderProfitMapper.selectMaxTime(1);
				SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String format = d.format(maxTime);
				// 首先查询到所有的商户提现记录
				merchantWithdrawalsVoList = iUnlineOrderProfitMapper.getMerchantWithdrawalsVoList(format);
				if (null == merchantWithdrawalsVoList || merchantWithdrawalsVoList.size() < 1) {
					logger.debug("无商户提现记录的数据");
					return result;
				}
				// 接下来执行将商户提现记录插入到供应链分润表
				System.out.println("--------------------");
				iUnlineOrderProfitMapper
						.insertUnlineSupplyChainProfitListForMerchantWithdrawals(merchantWithdrawalsVoList);
				System.out.println("--------------------");
			} else {
				// 第一次
				merchantWithdrawalsVoList = iUnlineOrderProfitMapper.getMerchantWithdrawalsVoList(null);
				if (null == merchantWithdrawalsVoList || merchantWithdrawalsVoList.size() < 1) {
					logger.debug("无商户提现记录的数据");
					return result;
				}
				// 接下来执行将商户提现记录插入到供应链分润表
				iUnlineOrderProfitMapper
						.insertUnlineSupplyChainProfitListForMerchantWithdrawals(merchantWithdrawalsVoList);
			}
			// 取到 merchantWithdrawalsVoList中的最大时间
			Date maxCreateDate = merchantWithdrawalsVoList.get(0).getCreateDate();
			// 插入时间 ph_merchant_withdrawals_into_profit 做个记录
			iUnlineOrderProfitMapper.insertWithdrawalsIntoProfit(maxCreateDate, 1);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("提取商户提现记录到分润表异常:" + e.getMessage());
			throw new BizException("提取商户提现记录到分润表异常");
		}
		return result;
	}

	/**
	 * 执行将代理商提现记录表的数据插入到线下订单供应链分润记录表
	 */
	public Result executiveAgentWithdrawalsIntoUnlineSupplychainProfit() {
		Result result = getResult(ResultEnum.SUCCESS);
		try {
			// 查询是否有时间 以此来判断是否是第一次插入时间(查询数量)
			Integer count = iUnlineOrderProfitMapper.selectMerchantWithdrawalsIntoProfitCount(2);
			List<AgentWithdrawalsVo> agentWithdrawalsVoList = null;
			if (count > 0) {// 证明不是第一次来执行
				// 查询到最大时间
				Date maxTime = iUnlineOrderProfitMapper.selectMaxTime(2);
				SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String format = d.format(maxTime);
				// 首先查询到所有的代理提现记录
				agentWithdrawalsVoList = iUnlineOrderProfitMapper.getAgentWithdrawalsVoList(format);
				if (null == agentWithdrawalsVoList || agentWithdrawalsVoList.size() < 1) {
					logger.debug("无代理提现记录的数据");
					return result;
				}
				// 接下来执行将代理提现记录插入到供应链分润表
				System.out.println("--------------------");
				iUnlineOrderProfitMapper.insertUnlineSupplyChainProfitListForAgentWithdrawals(agentWithdrawalsVoList);
				System.out.println("--------------------");
			} else {
				// 第一次
				agentWithdrawalsVoList = iUnlineOrderProfitMapper.getAgentWithdrawalsVoList(null);
				if (null == agentWithdrawalsVoList || agentWithdrawalsVoList.size() < 1) {
					logger.debug("无代理提现记录的数据");
					return result;
				}
				// 接下来执行将代理户提现记录插入到供应链分润表
				iUnlineOrderProfitMapper.insertUnlineSupplyChainProfitListForAgentWithdrawals(agentWithdrawalsVoList);
			}
			// 取到 merchantWithdrawalsVoList中的最大时间
			Date maxCreateDate = agentWithdrawalsVoList.get(0).getCreateDate();
			// 插入时间 ph_merchant_withdrawals_into_profit 做个记录
			iUnlineOrderProfitMapper.insertWithdrawalsIntoProfit(maxCreateDate, 2);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("提取代理提现记录到分润表异常:" + e.getMessage());
			throw new BizException("提取代理提现记录到分润表异常");
		}

		return result;
	};

	/**
	 * 修改线下订单供应链分润审核状态
	 * 
	 * @return
	 */
	public Result updateProfitStatues(UnlineSupplyChainProfit unlineSupplyChainProfit) {
		Result result = getResult(ResultEnum.SUCCESS);
		try {
			iUnlineOrderProfitMapper.updateProfitByPrimaryKey(unlineSupplyChainProfit);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("修改供应链订单审核状态异常:" + e.getMessage());
			result = getResult(ResultEnum.UPDATE_UNLINEORDERSUPPLYCHAINPROFIT_EXCEPTION);
			throw new BizException("修改供应链订单审核状态异常:90002");
		}
		return result;
	}

	/**
	 * 
	 * @Title: queryProvince
	 * @Description: 查询省
	 * @author WQiang
	 * @date 2017年3月30日 下午4:41:57
	 * @return
	 */
	public MessageInfo queryProvince() {
		try {
			return getMessageInfo(MessageEnum.SUCCESS, iUnlineManagerProfitMapper.getProvice());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 
	 * Title: queryCity Description:查询市
	 * 
	 * @author WQiang
	 * @date 2017年3月30日 下午6:00:00
	 * @param areaId
	 * @return
	 * @see com.ph.shopping.facade.profit.service.IProfitService#queryCity(long)
	 */
	@Override
	public MessageInfo queryCity(long areaId) {
		return getMessageInfo(MessageEnum.SUCCESS, iUnlineManagerProfitMapper.getCity(areaId));
	}

	/**
	 * 
	 * Title: queryCounty Description:查询区/县
	 * 
	 * @author WQiang
	 * @date 2017年3月30日 下午6:00:11
	 * @param areaId
	 * @return
	 * @see com.ph.shopping.facade.profit.service.IProfitService#queryCounty(long)
	 */
	@Override
	public MessageInfo queryCounty(long areaId) {
		return getMessageInfo(MessageEnum.SUCCESS, iUnlineManagerProfitMapper.getCounty(areaId));
	}

	/**
	 * 
	 * Title: addHunterProfit Description:新增猎头分润
	 * 
	 * @author WQiang
	 * @date 2017年4月5日 上午10:02:04
	 * @param requests
	 * @return
	 * @see com.ph.shopping.facade.profit.service.IProfitService#addHunterProfit(com.ph.shopping.facade.profit.request.HunterRequest)
	 */
	@Override
	public MessageInfo addHunterProfit(HunterRequest request) {
		HunterEntity hunterEntity = new HunterEntity();

		PositionDto positionDto = new PositionDto();
		positionDto.setProvinceId(request.getProvinceId());
		positionDto.setCityId(request.getCityId());
		positionDto.setCountyId(request.getCountyId());

		AgentVo agentVo = null;

		// 查询县代理
		List<AgentVo> countyAgency = iUnlineManagerProfitMapper.queryCountyAgency(positionDto);
		if (VerifyUtil.listIsNotNull(countyAgency)) {
			agentVo = countyAgency.get(0);
			hunterEntity.setXianName(agentVo.getAgentName());
			hunterEntity.setXianRName(agentVo.getPromoterName());
		}

		// 查询市代理
		List<AgentVo> cityAgency = iUnlineManagerProfitMapper.queryCityAgency(positionDto);
		if (VerifyUtil.listIsNotNull(cityAgency)) {
			agentVo = cityAgency.get(0);
			hunterEntity.setShiName(agentVo.getAgentName());
			hunterEntity.setShiRName(agentVo.getPromoterName());
		}

		double A = MoneyTransUtil.transDivisDouble(request.getOrderMoney());// 订单金额
		double C = MoneyTransUtil.transDivisDouble(request.getPhProfit());// 普惠分润

		hunterEntity.setMemberTel(request.getMemberTel());
		hunterEntity.setOrderMoney(request.getOrderMoney());
		hunterEntity.setPhProfit(request.getPhProfit());
		hunterEntity.setProvinceId(request.getProvinceId());
		hunterEntity.setCityId(request.getCityId());
		hunterEntity.setCountyId(request.getCountyId());
		hunterEntity.setTownId(request.getTownId());
		hunterEntity.setOrderNo(request.getOrderNo());
		hunterEntity.setHunterTel(request.getHunterTel());
		hunterEntity.setProfitTime(request.getProfitTime());

		hunterEntity.setHunterProfit(MoneyTransUtil.transMultiDouble(ProfitCalculation.getB(A, C)));
		hunterEntity.setChargeProfit(MoneyTransUtil.transMultiDouble(ProfitCalculation.getD(A)));
		hunterEntity.setPhChargeProft(MoneyTransUtil.transMultiDouble(ProfitCalculation.getE(A)));
		hunterEntity.setYstCHargeProfit(MoneyTransUtil.transMultiDouble(ProfitCalculation.getF(A)));

		if (VerifyUtil.isNotEmpty(hunterEntity.getShiName())) {
			hunterEntity.setShiProfit(MoneyTransUtil.transMultiDouble(ProfitCalculation.getG(A)));
			hunterEntity.setShiChainProfit(MoneyTransUtil.transMultiDouble(ProfitCalculation.getU(A)));
			if (VerifyUtil.isNotEmpty(hunterEntity.getShiRName())) {
				hunterEntity.setShiRProfit(MoneyTransUtil.transMultiDouble(ProfitCalculation.getK1(A)));
			} else {
				hunterEntity.setShiRProfit(0l);
			}
		} else {
			hunterEntity.setShiProfit(0l);
			hunterEntity.setShiRProfit(0l);
			hunterEntity.setShiChainProfit(0l);
		}

		if (VerifyUtil.isNotEmpty(hunterEntity.getXianName())) {
			hunterEntity.setXianProfit(MoneyTransUtil.transMultiDouble(ProfitCalculation.getH(A)));
			hunterEntity.setXianChainProfit(MoneyTransUtil.transMultiDouble(ProfitCalculation.getW(A)));
			if (VerifyUtil.isNotEmpty(hunterEntity.getXianRName())) {
				hunterEntity.setXianRProfit(MoneyTransUtil.transMultiDouble(ProfitCalculation.getK2(A)));
			} else {
				hunterEntity.setXianRProfit(0l);
			}
		} else {
			hunterEntity.setXianProfit(0l);
			hunterEntity.setXianRProfit(0l);
			hunterEntity.setXianChainProfit(0l);
		}

		// 管理费支出合计
		long chargeProfitTotal = hunterEntity.getShiProfit() + hunterEntity.getXianProfit()
				+ hunterEntity.getShiRProfit() + hunterEntity.getXianRProfit();
		// 管理费剩余
		long chargeProfitRemain = hunterEntity.getYstCHargeProfit() - chargeProfitTotal;
		hunterEntity.setChargeProfitTotal(chargeProfitTotal);
		hunterEntity.setChargeProfitRemain(chargeProfitRemain);

		hunterEntity.setChainProfit(MoneyTransUtil.transMultiDouble(ProfitCalculation.getR(A)));
		hunterEntity.setPhChainProfit(MoneyTransUtil.transMultiDouble(ProfitCalculation.getS(A)));
		hunterEntity.setYstChainProfit(MoneyTransUtil.transMultiDouble(ProfitCalculation.getT(A)));

		// 供应链支出合计
		long chainProfitTotal = hunterEntity.getShiChainProfit() + hunterEntity.getXianChainProfit();
		// 供应链剩余
		long chainProfitRemain = hunterEntity.getYstChainProfit() - chainProfitTotal;

		hunterEntity.setChainProfitTotal(chainProfitTotal);
		hunterEntity.setChainProfitRemain(chainProfitRemain);

		hunterEntity.setIsAccept(1);// 默认接受

		int res = iHunterMapper.insertSelective(hunterEntity);
		if (res != 1) {
			return getMessageInfo(MessageEnum.NO_RESOURCE);
		}

		return getMessageInfo(MessageEnum.SUCCESS);
	}

	/**
	 * 
	 * Title: getAreaList Description:根据乡镇id获取省市县列表
	 * 
	 * @author WQiang
	 * @date 2017年4月6日 上午10:17:45
	 * @param townId
	 * @return
	 * @see com.ph.shopping.facade.profit.service.IProfitService#getAreaList(long)
	 */
	@Override
	public MessageInfo getAreaList(long townId) {
		return getMessageInfo(MessageEnum.SUCCESS, iHunterMapper.getAreaByTownId(townId));
	}

	/**
	 * 
	 * Title: getTownList Description:根据县id获取乡镇列表
	 * 
	 * @author WQiang
	 * @date 2017年4月6日 上午10:32:17
	 * @param countyId
	 * @return
	 * @see com.ph.shopping.facade.profit.service.IProfitService#getTownList(long)
	 */
	@Override
	public MessageInfo getTownList(long countyId) {
		return getMessageInfo(MessageEnum.SUCCESS, iHunterMapper.getTowns(countyId));
	}

	@Override
	public MessageInfo getProvinces() {

		return getMessageInfo(MessageEnum.SUCCESS, iHunterMapper.getPosition());
	}

	@Override
	public MessageInfo getCitys(long provinceId) throws Exception {

		return getMessageInfo(MessageEnum.SUCCESS, iHunterMapper.getCityByPid(provinceId));
	}

	@Override
	public MessageInfo getCountys(long cityId) throws Exception {

		return getMessageInfo(MessageEnum.SUCCESS, iHunterMapper.getCountyByCid(cityId));
	}

	@Override
	public MessageInfo getTowns(long countyId) throws Exception {

		return getMessageInfo(MessageEnum.SUCCESS, iHunterMapper.getTownByCid(countyId));
	}

	/**
	 * 
	 * Title: getHunterProfits Description:查询猎头分润
	 * 
	 * @author WQiang
	 * @date 2017年4月12日 下午2:24:27
	 * @param pageNum
	 * @param pageSize
	 * @see com.ph.shopping.facade.profit.service.IProfitService#getHunterProfits(int,
	 *      int)
	 */
	@Override
	public Result getHunterProfits(int pageNum, int pageSize, String orderNo) throws Exception {
		PageHelper.startPage(pageNum, pageSize);
		List<HunterProfitVo> list = iHunterMapper.getHunterProfits(orderNo);
		for (HunterProfitVo vo : list) {
			vo.setOrderMoney(MoneyTransUtil.transDivisDouble(vo.getOrderMoney1()));
			vo.setHunterProfit(MoneyTransUtil.transDivisDouble(vo.getHunterProfit1()));
			vo.setPhProfit(MoneyTransUtil.transDivisDouble(vo.getPhProfit1()));
			vo.setChargeProfit(MoneyTransUtil.transDivisDouble(vo.getChargeProfit1()));
			vo.setPhChargeProft(MoneyTransUtil.transDivisDouble(vo.getPhChargeProft1()));
			vo.setYstCHargeProfit(MoneyTransUtil.transDivisDouble(vo.getYstCHargeProfit1()));
			vo.setShiProfit(MoneyTransUtil.transDivisDouble(vo.getShiProfit1()));
			vo.setXianProfit(MoneyTransUtil.transDivisDouble(vo.getXianProfit1()));
			vo.setShiRProfit(MoneyTransUtil.transDivisDouble(vo.getShiRProfit1()));
			vo.setXianRProfit(MoneyTransUtil.transDivisDouble(vo.getXianRProfit1()));
			vo.setChargeProfitTotal(MoneyTransUtil.transDivisDouble(vo.getChargeProfitTotal1()));
			vo.setChargeProfitRemain(MoneyTransUtil.transDivisDouble(vo.getChargeProfitRemain1()));

			vo.setChainProfit(MoneyTransUtil.transDivisDouble(vo.getChainProfit1()));
			vo.setPhChainProfit(MoneyTransUtil.transDivisDouble(vo.getPhChainProfit1()));
			vo.setYstChainProfit(MoneyTransUtil.transDivisDouble(vo.getYstChainProfit1()));
			vo.setShiChainProfit(MoneyTransUtil.transDivisDouble(vo.getShiChainProfit1()));
			vo.setXianChainProfit(MoneyTransUtil.transDivisDouble(vo.getXianChainProfit1()));
			vo.setChainProfitTotal(MoneyTransUtil.transDivisDouble(vo.getChainProfitTotal1()));
			vo.setChainProfitRemain(MoneyTransUtil.transDivisDouble(vo.getChainProfitRemain1()));
		}
		PageInfo<HunterProfitVo> info = new PageInfo<HunterProfitVo>(list);
		return getResult(ResultEnum.SUCCESS, info.getList(), info.getTotal());
	}

	/**
	 * 
	 * Title: audit Description:审核操作
	 * 
	 * @author WQiang
	 * @date 2017年4月13日 下午1:42:24
	 * @param profitId
	 * @param status
	 * @param id
	 * @return
	 * @see com.ph.shopping.facade.profit.service.IProfitService#audit(java.lang.Long,
	 *      java.lang.Integer, java.lang.Long)
	 */
	@Override
	public Result audit(long profitId, int status, long userId, int tableType, String reason) {
		int res = 0;
		if (tableType == 1) {
			res = iUnlineManagerProfitMapper.audit(profitId, status, userId, TableNameContants.MANAGER, reason);
		} else if (tableType == 2) {
			res = iUnlineManagerProfitMapper.audit(profitId, status, userId, TableNameContants.HUNTER, reason);
		}
		if (res == 1) {
			return getResult(ResultEnum.SUCCESS);
		} else {
			return getResult(ResultEnum.FAIL);
		}

	}

	/**
	 * 
	 * Title: exportHunterProfits Description: 导出猎头分润
	 * 
	 * @author WQiang
	 * @date 2017年4月18日 下午5:56:04
	 * @param orderNo
	 * @return
	 * @see com.ph.shopping.facade.profit.service.IProfitService#exportHunterProfits(java.lang.String)
	 */
	@Override
	public List<HunterProfitVo> exportHunterProfits(String orderNo) {
		List<HunterProfitVo> list = iHunterMapper.getHunterProfits(orderNo);
		if (VerifyUtil.listIsNotNull(list)) {
			for (HunterProfitVo vo : list) {
				vo.setOrderMoney(MoneyTransUtil.transDivisDouble(vo.getOrderMoney1()));
				vo.setHunterProfit(MoneyTransUtil.transDivisDouble(vo.getHunterProfit1()));
				vo.setPhProfit(MoneyTransUtil.transDivisDouble(vo.getPhProfit1()));
				vo.setChargeProfit(MoneyTransUtil.transDivisDouble(vo.getChargeProfit1()));
				vo.setPhChargeProft(MoneyTransUtil.transDivisDouble(vo.getPhChargeProft1()));
				vo.setYstCHargeProfit(MoneyTransUtil.transDivisDouble(vo.getYstCHargeProfit1()));
				vo.setShiProfit(MoneyTransUtil.transDivisDouble(vo.getShiProfit1()));
				vo.setXianProfit(MoneyTransUtil.transDivisDouble(vo.getXianProfit1()));
				vo.setShiRProfit(MoneyTransUtil.transDivisDouble(vo.getShiRProfit1()));
				vo.setXianRProfit(MoneyTransUtil.transDivisDouble(vo.getXianRProfit1()));
				vo.setChargeProfitTotal(MoneyTransUtil.transDivisDouble(vo.getChargeProfitTotal1()));
				vo.setChargeProfitRemain(MoneyTransUtil.transDivisDouble(vo.getChargeProfitRemain1()));

				vo.setChainProfit(MoneyTransUtil.transDivisDouble(vo.getChainProfit1()));
				vo.setPhChainProfit(MoneyTransUtil.transDivisDouble(vo.getPhChainProfit1()));
				vo.setYstChainProfit(MoneyTransUtil.transDivisDouble(vo.getYstChainProfit1()));
				vo.setShiChainProfit(MoneyTransUtil.transDivisDouble(vo.getShiChainProfit1()));
				vo.setXianChainProfit(MoneyTransUtil.transDivisDouble(vo.getXianChainProfit1())); 
				vo.setChainProfitTotal(MoneyTransUtil.transDivisDouble(vo.getChainProfitTotal1()));
				vo.setChainProfitRemain(MoneyTransUtil.transDivisDouble(vo.getChainProfitRemain1()));
			}
			return list;
		} else {
			return null;
		}
	}

}
